package com.xzz.thread;

/**
 * @author: hhz
 * @createDate: 2021-4-16
 */

import java.util.concurrent.locks.ReentrantLock;

/**
 * 三个线程分别打印 A，B，C，要求这三个线程一起运行，打印 n 次，输出形如“ABCABCABC....”的字符串
 */
public class PrintABCUsingLock {
    private int n;
    private int state;
    private ReentrantLock lock = new ReentrantLock();

    public PrintABCUsingLock(int n) {
        this.n = n;
    }

    private void printName(String name, int targetN) {
        for (int i = 0; i < n; ) {
            lock.lock();
            if (state % 3 == targetN) {
                state++;
                i++;
                System.out.print(name);
            }
            lock.unlock();
        }

    }

    public static void main(String[] args) {
        PrintABCUsingLock usingLock = new PrintABCUsingLock(100);
        new Thread(() -> {
            usingLock.printName("A", 0);
        }, "A").start();
        new Thread(() -> {
            usingLock.printName("B", 1);
        }, "B").start();
        new Thread(() -> {
            usingLock.printName("C", 2);
        }, "C").start();

    }

}
